package com.graduationdesign.zengyan.graduationdesignapp.ui.activities.profile;

import android.annotation.TargetApi;
import android.os.Build;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.graduationdesign.zengyan.graduationdesignapp.BaseApplication;
import com.graduationdesign.zengyan.graduationdesignapp.R;
import com.graduationdesign.zengyan.graduationdesignapp.dataLayer.dataBase.RecentlyUsed;
import com.graduationdesign.zengyan.graduationdesignapp.dataLayer.model.Event;
import com.graduationdesign.zengyan.graduationdesignapp.dataLayer.model.User;
import com.graduationdesign.zengyan.graduationdesignapp.dataLayer.profileRepository.DataGenerator;
import com.graduationdesign.zengyan.graduationdesignapp.ui.activities.PresenterInjection;
import com.graduationdesign.zengyan.graduationdesignapp.ui.activities.UiInjection;
import com.graduationdesign.zengyan.graduationdesignapp.ui.activities.commonlyUsed.SlideCardAdapter;
import com.graduationdesign.zengyan.graduationdesignapp.ui.base.BaseActivity;
import com.graduationdesign.zengyan.graduationdesignapp.ui.base.BaseUiView;
import com.graduationdesign.zengyan.graduationdesignapp.ui.base.IntentKey;
import com.graduationdesign.zengyan.graduationdesignapp.ui.base.errorhandle.CommonErrorView;
import com.graduationdesign.zengyan.graduationdesignapp.ui.contact.ProfileContact;
import com.graduationdesign.zengyan.graduationdesignapp.ui.presenter.ProfilePresenter;
import com.graduationdesign.zengyan.graduationdesignapp.utils.Config;
import com.graduationdesign.zengyan.graduationdesignapp.utils.PhoneUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;

public class ProfileActivity extends BaseActivity implements ProfileContact.ShowPeopleInfo ,View.OnClickListener, ProfileContact.ShowEventsISignUp {
    private String  stuNum ;
    private ProfileContact.Presenter presenter;

    @BindView(R.id.name)
    TextView mName;

    @BindView(R.id.message)
    FloatingActionButton messageBtn;

    @BindView(R.id.long_call)
    FloatingActionButton longCallBtn;

    @BindView(R.id.short_call)
    FloatingActionButton shortCallBtn;

    @BindView(R.id.base_ui)
    BaseUiView baseUiView;

    @BindView(R.id.image)
    SimpleDraweeView avaterImage;

    @BindView(R.id.event_view_pager)
    ViewPager eventViewPager;

    @BindView(R.id.bg)
    SimpleDraweeView bgImage;

    private User mUser;
    private SlideCardAdapter<Event> slideCardAdapter;
    private List<Event> mData = new ArrayList<>();



    @Override
    public void showPeopleInfo(User user) {
        mUser = user;
        mName.setText("「"+user.getName()+"」");
        avaterImage.setImageURI(Config.imageUrl+user.getAvatarUrl());
        bgImage.setImageURI(Config.imageUrl+user.getBgUrl());


    }

    private void saveRecentlyUsed(User user) {
        Observable.just(user)
                .observeOn(Schedulers.io())
                .subscribe(user1 -> {
                    List<RecentlyUsed> result = BaseApplication.mDatabase.getRecentlyUsedDao().findDataByStuNum(user.getStudentNum());
                    if (!result.isEmpty()) return;
                    RecentlyUsed recentlyUsed = new RecentlyUsed();
                    recentlyUsed.setUser(user1);
                    BaseApplication.mDatabase.getRecentlyUsedDao().insertAll(recentlyUsed);
                });
    }


    @Override
    protected int provideLayoutId() {
        return R.layout.activity_profile;
    }

    @Override
    protected Boolean isFullScreen() {
        return true;
    }

    @Override
    protected void initArgument() {
        stuNum = getIntent().getStringExtra(IntentKey.STIUNUM);
    }

    @Override
    protected void initPresenter() {
        presenter = PresenterInjection.provideProfilePresenter(
                ProfilePresenter
                        .newBuilder()
                        .setMLoadingView(baseUiView)
                        .setBaseErrorView(new CommonErrorView(this))
                        .setShowEventsISignUp(this)
                        .setShowPeopleInfo(this)
        );

    }

    @Override
    protected void initToolbar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    protected void initView() {
        final CollapsingToolbarLayout collapsing_toolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
        ((AppBarLayout) findViewById(R.id.app_bar_layout)).addOnOffsetChangedListener((appBarLayout, verticalOffset) -> {
            int min_height = ViewCompat.getMinimumHeight(collapsing_toolbar) * 2;
            float scale = (float) (min_height + verticalOffset) / min_height;
            avaterImage.setScaleX(scale >= 0 ? scale : 0);
            avaterImage.setScaleY(scale >= 0 ? scale : 0);
        });
        messageBtn.setOnClickListener(this);
        longCallBtn.setOnClickListener(this);
        shortCallBtn.setOnClickListener(this);
        initViewPaper();
    }

    private void initViewPaper() {
        slideCardAdapter = new SlideCardAdapter<Event>(this,R.layout.item_slice_event_small_card,mData) {
            @TargetApi(Build.VERSION_CODES.M)
            @Override
            public void bind(View rootview, Event data, int position) {
                RelativeLayout mLytParent;
                CardView mCard;
                TextView mTitle,mDesc;
                ImageView mBg;
                Button mSignUp;
                mCard = (CardView) rootview.findViewById(R.id.card);
                mTitle = (TextView) rootview.findViewById(R.id.title);
                mBg = (ImageView) rootview.findViewById(R.id.bg);


                mTitle.setText(data.getTitle());
                List<Integer> integers = DataGenerator.getNatureImages(ProfileActivity.this);
                mBg.setBackgroundResource(integers.get(DataGenerator.randInt(integers.size()-1)));
            }
        };
        eventViewPager.setAdapter(slideCardAdapter);

        eventViewPager.setPageMargin(getResources().getDimensionPixelOffset(R.dimen.viewpager_layout_margin_overlap_payment));
        eventViewPager.setOffscreenPageLimit(slideCardAdapter.getCount());


    }

    @Override
    protected void start() {
        presenter.loadPeople(stuNum,baseUiView);
        presenter.loadEventsISignUp(stuNum);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
//        if (mUser.getStudentNum().equals(AccountManager.getInstance().getCurrentStuNum())) {
//            getMenuInflater().inflate(R.menu.menu_profile_edit, menu);
//        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_edit:
                ProfileActivity.this.startActivity(UiInjection.provideProfileEdit(this));
                break;

        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.message:
                ArrayList<String> list = new ArrayList<>();
                list.add(mUser.getPhone());
                PhoneUtils.message(this,list);
                break;
            case R.id.long_call:
                PhoneUtils.call(this,mUser.getPhone());
                break;
            case R.id.short_call:
                PhoneUtils.call(this,mUser.getShortPhone());
                break;

        }
        saveRecentlyUsed(mUser);

    }

    @Override
    public void showEventsISignUp(List<Event> list) {
        mData.clear();
        mData.addAll(list);
        slideCardAdapter.notifyDataSetChanged();
    }
}
